package blackpai.backend.controller;

import blackpai.backend.entity.Manager;
import blackpai.backend.service.ManagerService;
import blackpai.backend.vo.Result;
import blackpai.backend.vo.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("manager")
public class ManagerController {

    @Autowired
    private ManagerService managerService;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("findAllManagers")
    public Result findAllManagers(HttpServletRequest request){
        List<Manager> managers = managerService.findAllManagers();
        Result result = new Result();
        result.setStatus(0);
        result.setData(managers);
        return result;
    }

    @RequestMapping("login")
    public Result login(String username, String password, String verifycode){
        List<String> securityCode = restTemplate.getForObject("http://redis-server/redis/getVerifyCode", List.class);
        Result result = null;
        try {
            for (String o : securityCode) {
                if(o.equals(verifycode)){
                    Token token = managerService.managerLogin(username, password);
                    result = new Result();
                    result.setStatus(0);
                    result.setData(token);
                    result.setMessags("登陆成功");
                    return result;
                }
            }
            throw new RuntimeException("验证码错误");
        }catch (Exception e){
            e.printStackTrace();
            result = new Result();
            result.setStatus(1);
            result.setMessags(e.getMessage());
        }
        return result;
    }

    @RequestMapping("saveManager")
    public Result saveManager(Manager manager){
        System.out.println(manager.getUsername());
        return managerService.saveManager(manager);
    }

    @RequestMapping("updateManager")
    public Result updateManager(Manager manager){
        return managerService.updateManager(manager);
    }

    @RequestMapping(value = "/test/{list}")
    public String test(String test){
        return test;
    }

}
